import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

class PlatformInAppBrowser extends ChromeSafariBrowser with WidgetsBindingObserver {
  Brightness? _deviceBrightness;

  @override
  void onOpened() {
    Future.delayed(const Duration(milliseconds: 200), () {
      _deviceBrightness = WidgetsBinding.instance.platformDispatcher.platformBrightness;

      SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
        statusBarBrightness: _deviceBrightness,
      ));
      WidgetsBinding.instance.addObserver(this);
    });
  }

  @override
  void didChangePlatformBrightness() {
    super.didChangePlatformBrightness();

    if (_deviceBrightness != WidgetsBinding.instance.platformDispatcher.platformBrightness) {
      _deviceBrightness = WidgetsBinding.instance.platformDispatcher.platformBrightness;

      SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
        statusBarBrightness: _deviceBrightness,
      ));
    }
  }

  Future<void> openUrl({
    required String url,
    required Color controlTintColorIos,
    bool readerViewIos = true,
  }) async {
    await open(
      url: Uri.parse(url),
      options: ChromeSafariBrowserClassOptions(
        android: AndroidChromeCustomTabsOptions(
          enableUrlBarHiding: true,
          shareState: CustomTabsShareState.SHARE_STATE_OFF,
          showTitle: true,
        ),
        ios: IOSSafariOptions(
          entersReaderIfAvailable: readerViewIos,
          barCollapsingEnabled: true,
          preferredControlTintColor: controlTintColorIos,
        ),
      ),
    );
  }
}
